package com.xnx3.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author Mikey
 * @version 1.0
 * @date 2021/10/21 19:33
 * @description
 */

@Component
@Slf4j
public class HttpClientUtil {
    public static final String CONTENT_TYPE = "application/json";
    public static final String CHARSET = "UTF-8";
    public static final int CONNTIMEOUT = 120000;
    public static final int READTIMEOUT = 120000;
    private static HttpClient client = null;
    private static RequestConfig requestConfig = null;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();

        RequestConfig.Builder customReqConf = RequestConfig.custom();
        customReqConf.setConnectTimeout(CONNTIMEOUT);
        customReqConf.setSocketTimeout(READTIMEOUT);
        requestConfig = customReqConf.build();
    }


    /**
     * get
     * 发送get请求
     *
     * @param host    主机地址
     * @param path    请求路径
     * @param headers 请求头数据,使用map封装
     * @param querys  请求参数,使用map封装
     * @return
     * @throws Exception
     */
    public static String doGet(String host, String path,
                               Map<String, String> headers,
                               Map<String, String> querys) {
        HttpClient httpClient = wrapClient(host);
        String ret = "";
        HttpGet request = null;
        HttpResponse resp = null;
        String uri = null;
        try {
            uri = buildUrl(host, path, querys);
            request = new HttpGet(uri);
            if (null != headers) {
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }
            }
            request.setConfig(requestConfig);
            resp = httpClient.execute(request);
            ret = resultPotting(resp, uri);
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (ClientProtocolException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            request.releaseConnection();
            if (null != resp) {
                EntityUtils.consumeQuietly(resp.getEntity());
            }
            if (uri.startsWith("https") && httpClient != null
                    && httpClient instanceof CloseableHttpClient) {
                try {
                    ((CloseableHttpClient) httpClient).close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
        return ret;
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @param bodys   请求体,使用map封装
     * @return
     * @throws Exception
     */
    public static String doPost(String host, String path,
                                Map<String, String> headers,
                                Map<String, String> querys,
                                Map<String, String> bodys) {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = null;
        String ret = "";
        HttpResponse resp = null;
        String uri = null;
        try {
            uri = buildUrl(host, path, querys);
            request = new HttpPost(uri);
            if (headers != null) {
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }
            }

            if (bodys != null) {
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

                for (String key : bodys.keySet()) {
                    nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
                formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
                request.setEntity(formEntity);
            }
            request.setConfig(requestConfig);
            resp = httpClient.execute(request);
            ret = resultPotting(resp, uri);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        } finally {
            request.releaseConnection();
            if (null != resp) {
                EntityUtils.consumeQuietly(resp.getEntity());
            }
            if (uri.startsWith("https") && httpClient != null
                    && httpClient instanceof CloseableHttpClient) {
                try {
                    ((CloseableHttpClient) httpClient).close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
        return ret;
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static String doPost(String host, String path,
                                Map<String, String> headers,
                                Map<String, String> querys,
                                String body) {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = null;
        HttpResponse resp = null;
        String ret = "";
        String uri = null;
        try {
            uri = buildUrl(host, path, querys);
            log.info("getYunshuToken=========>" + uri);
            request = new HttpPost(uri);
/*            RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
            request.setConfig(requestConfig);*/
            if (headers != null) {
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    request.addHeader(e.getKey(), e.getValue());
                }
            }

            if (StringUtils.isNotBlank(body)) {
                HttpEntity entity = new StringEntity(body, ContentType.create(CONTENT_TYPE, CHARSET));
                request.setEntity(entity);
            }
            request.setConfig(requestConfig);
            resp = httpClient.execute(request);
            log.info("resp======>"+resp);
            return resultPotting(resp, uri);
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (ClientProtocolException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            request.releaseConnection();
            if (null != resp) {
                EntityUtils.consumeQuietly(resp.getEntity());
            }
            if (uri.startsWith("https") && httpClient != null
                    && httpClient instanceof CloseableHttpClient) {
                try {
                    ((CloseableHttpClient) httpClient).close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
//
        return ret;
    }

    /**
     * Post stream
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static String doPost(String host, String path,
                                Map<String, String> headers,
                                Map<String, String> querys,
                                byte[] body) {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = null;
        HttpResponse resp = null;
        String ret = "";
        String uri = null;
        try {
            uri = buildUrl(host, path, querys);
            request = new HttpPost(uri);
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }

            if (body != null) {
                request.setEntity(new ByteArrayEntity(body));
            }
            request.setConfig(requestConfig);
            resp = httpClient.execute(request);
            ret = resultPotting(resp, uri);
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (ClientProtocolException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            request.releaseConnection();
            if (null != resp) {
                EntityUtils.consumeQuietly(resp.getEntity());
            }
            if (uri.startsWith("https") && httpClient != null
                    && httpClient instanceof CloseableHttpClient) {
                try {
                    ((CloseableHttpClient) httpClient).close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
        return ret;
    }

    /**
     * Put String
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static String doPut(String host, String path,
                               Map<String, String> headers,
                               Map<String, String> querys,
                               String body) {
        HttpClient httpClient = wrapClient(host);
        String uri = null;
        HttpResponse resp = null;
        HttpPut request = null;
        try {
            uri = buildUrl(host, path, querys);
            request = new HttpPut(uri);
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }

            if (StringUtils.isNotBlank(body)) {
                request.setEntity(new StringEntity(body, "utf-8"));
            }
            request.setConfig(requestConfig);
            resp = httpClient.execute(request);
            return resultPotting(resp, uri);
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (ClientProtocolException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            request.releaseConnection();
            if (null != resp) {
                EntityUtils.consumeQuietly(resp.getEntity());
            }
            if (uri.startsWith("https") && httpClient != null
                    && httpClient instanceof CloseableHttpClient) {
                try {
                    ((CloseableHttpClient) httpClient).close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
        return "";
    }

    /**
     * Put stream
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body) {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = null;
        HttpResponse resp = null;
        String uri = null;
        try {
            uri = buildUrl(host, path, querys);
            request = new HttpPut(uri);
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }

            if (body != null) {
                request.setEntity(new ByteArrayEntity(body));
            }
            request.setConfig(requestConfig);
            resp = httpClient.execute(request);
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (ClientProtocolException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            request.releaseConnection();
            if (null != resp) {
                EntityUtils.consumeQuietly(resp.getEntity());
            }
            if (uri.startsWith("https") && httpClient != null
                    && httpClient instanceof CloseableHttpClient) {
                try {
                    ((CloseableHttpClient) httpClient).close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
        return resp;
    }

    /**
     * Delete
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));

        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        request.setConfig(requestConfig);
        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }
        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }


    private static HttpClient sslClient() {
        try {
            // 在调用SSL之前需要重写验证方法，取消检测SSL
            X509TrustManager trustManager = new X509TrustManager() {
                @Override public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override public void checkClientTrusted(X509Certificate[] xcs, String str) {}
                @Override public void checkServerTrusted(X509Certificate[] xcs, String str) {}
            };
            SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            ctx.init(null, new TrustManager[] { trustManager }, null);
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            // 创建Registry
            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                    .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
                    .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https",socketFactory).build();
            // 创建ConnectionManager，添加Connection配置信息
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
                    .setDefaultRequestConfig(requestConfig).build();
            return closeableHttpClient;
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }


    /**
     * @description:封装接口调用返回结果
     * @param: HttpResponse url
     * @return: java.lang.String
     */
    private static String resultPotting(HttpResponse res, String url) throws IOException {
        String result = "";
        log.info("getHeadersToken====>"+res);
        if (res.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(res.getEntity(), CHARSET);
            log.info("getResultEntity====>" + result);
        } else {
            log.info("HTTP(S) 请求，状态异常：" + res.getStatusLine().getStatusCode() + " | " + url);
            throw new BusinessException("HTTP(S) 请求，状态异常：" + res.getStatusLine().getStatusCode() + "|" + url);
        }
        return result;
    }

    public static String xmlPost(String urlStr, String xmlInfo){
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            // 一定要设置报文格式，否则发送失败
            con.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter out = null;
            try {
                out = new OutputStreamWriter(con.getOutputStream());
            } catch (ConnectException e) {
                throw new BusinessException("Connection refused");
            }
            log.info("HTTP(S) 请求，xmlInfo信息：" + xmlInfo);
            out.write(new String(xmlInfo.getBytes("UTF-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (MalformedURLException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

    public static String doPayPost(String uri, String body,String tokenid) {
        HttpPost request = null;
        HttpResponse resp = null;
        String ret = "";
        try {
            request = new HttpPost(uri);
            request.addHeader("tokenid", tokenid);
            if (StringUtils.isNotBlank(body)) {
                HttpEntity entity = new StringEntity(body, ContentType.create(CONTENT_TYPE, CHARSET));
                request.setEntity(entity);
            }

            request.setConfig(requestConfig);
            resp = client.execute(request);
            return resultPotting(resp, uri);
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (ClientProtocolException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            request.releaseConnection();
            if (null != resp) {
                EntityUtils.consumeQuietly(resp.getEntity());
            }
        }
        return ret;
    }

//    public static String doBankPost(String url, String body) {
//        HttpPost request = null;
//        HttpResponse resp = null;
//        String ret = "";
//        try {
//            request = new HttpPost(url);
//            if (StringUtils.isNotBlank(body)) {
//                HttpEntity entity = new StringEntity(body, ContentType.create(CONTENT_TYPE, CHARSET));
//                request.setEntity(entity);
//            }
//            request.setConfig(requestConfig);
//            resp = client.execute(request);
//            return resultPotting(resp, url);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            request.releaseConnection();
//            if (null != resp) {
//                EntityUtils.consumeQuietly(resp.getEntity());
//            }
//        }
//        return ret;
//    }

//    public static String doMaskGet(Object object,String type) {
//        HttpClient httpClient =  new DefaultHttpClient();
//        if(ENDPOINT.startsWith("https://")){
//            httpClient = sslClient();
//        }
//        String ret = "";
//        HttpGet request = null;
//        HttpResponse resp = null;
//        String uri = null;
//        try {
//            uri = DataMaskUtil.buildUrl(object, "GET", type);
//            log.info("getDataMaskURI=========>" + uri);
//            request = new HttpGet(uri);
//            request.setConfig(requestConfig);
//            resp = httpClient.execute(request);
//            log.info("resp======>"+resp);
//            ret = resultPotting(resp, uri);
//
//        } catch (UnsupportedEncodingException e) {
////            e.printStackTrace();
//            log.error(e.getMessage());
//        } catch (ClientProtocolException e) {
////            e.printStackTrace();
//            log.error(e.getMessage());
//        } catch (IOException e) {
////            e.printStackTrace();
//            log.error(e.getMessage());
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        } finally{
//            request.releaseConnection();
//            if (null != resp) {
//                EntityUtils.consumeQuietly(resp.getEntity());
//            }
//        }
//        return ret;
//    }
//
//
//    public static String doMaskPost(Object object,String type) {
//        HttpClient httpClient = new DefaultHttpClient();
//        if(ENDPOINT.startsWith("https://")){
//            httpClient = sslClient();
//        }
//        HttpPost request = null;
//        HttpResponse resp = null;
//        String ret = "";
//        String uri = null;
//        try {
//            uri = DataMaskUtil.buildUrl(object, "POST", type);
//            log.info("getDataMaskURI=========>" + uri);
//            request = new HttpPost(uri);
//            request.setConfig(requestConfig);
//            resp = httpClient.execute(request);
//            log.info("resp======>"+resp);
//            return resultPotting(resp, uri);
//        } catch (UnsupportedEncodingException e) {
//            log.error(e.getMessage());
//        } catch (ClientProtocolException e) {
//            log.error(e.getMessage());
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        } finally {
//            request.releaseConnection();
//            if (null != resp) {
//                EntityUtils.consumeQuietly(resp.getEntity());
//            }
//        }
//        return ret;
//    }
}
